package com.fyy.utils.listener;

import com.fyy.utils.string.SystemOut;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.HiddenFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.concurrent.TimeUnit;

@Component
public class FileListenerFactory {

    @Autowired
    private SystemOut systemOut;

    //监听路径
    private final String monitorDir = "D:\\";

    //设置轮询时间
    private final long interval = TimeUnit.SECONDS.toMillis(1);

    public FileAlterationMonitor getMonitor() {
//        //目录过滤器
//        IOFileFilter directories = FileFilterUtils.and(
//                FileFilterUtils.directoryFileFilter(),
//                HiddenFileFilter.VISIBLE);
        //文件过滤器
        IOFileFilter files = FileFilterUtils.and(
                FileFilterUtils.fileFileFilter(),
                FileFilterUtils.suffixFileFilter(".txt"));
        //IOFileFilter filter = FileFilterUtils.or(directories, files);
        IOFileFilter filter = FileFilterUtils.or(files);
        //装配过滤器
        FileAlterationObserver observer = new FileAlterationObserver(new File(monitorDir), filter);
        //向监听者添加监听器，并注入业务
        observer.addListener(new FileListener(systemOut));
        return new FileAlterationMonitor(interval,observer);
    }

}
